import React, { useState, useEffect } from 'react';
import { Form, Input, Button, Typography, message } from 'antd';
import { UserOutlined, LockOutlined } from '@ant-design/icons';
import { getCaptcha, register } from '@/views/login/api';
import { useNavigate } from 'react-router-dom';

const { Title } = Typography;

const Register = () => {
    const [captcha, setCaptcha] = useState();
    const [captchaKey, setCaptchaKey] = useState();
    const navigate = useNavigate();

    const refreshCaptcha = () => {
        getCaptcha().then((resp) => {
            setCaptcha(resp.data.image);
            setCaptchaKey(resp.data.key);
        });
    }

    // 注册处理函数
    const registerHandler = (registerForm) => {
        registerForm.certificate = btoa(encodeURIComponent(registerForm.certificate));
        delete registerForm.confirmPassword;
        let form = {
            data: registerForm,
            captchaKey
        }
        register(form).then(resp => {
            if (resp.data) {
                message.success('注册成功');
                navigate('/login');
            }
        }).catch(e => {
            console.error(e);
        });
    };

    useEffect(() => {
        refreshCaptcha();
    }, []);

    return (
        <div style={{
            backgroundImage: `url(${'/src/assets/img/login-bg.jpg'})`,
            backgroundSize: 'cover',
            backgroundPosition: 'center',
            minHeight: '100vh',
            display: 'flex',
            justifyContent: 'center',
            alignItems: 'center'
        }}>
            <Form
                name="normal_register"
                className="register-form"
                onFinish={registerHandler}
                style={{
                    backgroundColor: 'rgba(255, 255, 255, 0.8)',
                    padding: '50px',
                    borderRadius: '8px',
                    width: '450px',
                    border: '1px solid #1890ff'
                }}
            >
                <Title level={3} style={{ textAlign: 'center', marginBottom: '24px' }}>注册账号</Title>
                <Form.Item
                    name="type"
                    hidden
                    initialValue="PASSWORD"
                >
                    <Input type='hidden' />
                </Form.Item>
                <Form.Item
                    name="username"
                    rules={[{ required: true, message: '请输入用户名!' }]}
                >
                    <Input
                        prefix={<UserOutlined />}
                        placeholder="用户名"
                        style={{ height: '40px', fontSize: '16px' }}
                    />
                </Form.Item>

                <Form.Item
                    name="certificate"
                    rules={[{ required: true, message: '请输入密码!' }]}
                >
                    <Input
                        prefix={<LockOutlined />}
                        type="password"
                        placeholder="密码"
                        style={{ height: '40px', fontSize: '16px' }}
                    />
                </Form.Item>

                <Form.Item
                    name="confirmPassword"
                    dependencies={['certificate']}
                    rules={[
                        { required: true, message: '请确认密码!' },
                        ({ getFieldValue }) => ({
                            validator(_, value) {
                                if (!value || getFieldValue('certificate') === value) {
                                    return Promise.resolve();
                                }
                                return Promise.reject(new Error('两次输入的密码不匹配!'));
                            },
                        }),
                    ]}
                >
                    <Input
                        prefix={<LockOutlined />}
                        type="password"
                        placeholder="确认密码"
                        style={{ height: '40px', fontSize: '16px' }}
                    />
                </Form.Item>

                <Form.Item
                    name="captcha"
                    rules={[{ required: true, message: '请输入验证码!' }]}
                >
                    <div style={{ display: 'flex', alignItems: 'center' }}>
                        <Input
                            placeholder="验证码"
                            style={{
                                width: '100%',
                                height: '40px',
                                marginRight: '20px',
                                fontSize: '16px'
                            }}
                        />
                        <span style={{ width: '110px', height: '38px', padding: '4px 10px', backgroundColor: '#fff', borderRadius: 5 }}>
                            <img
                                src={captcha}
                                alt="验证码"
                                style={{
                                    width: '90px',
                                    height: '30px',
                                    cursor: 'pointer',
                                }}
                                onClick={refreshCaptcha}
                            />
                        </span>
                    </div>
                </Form.Item>

                <Form.Item>
                    <Button
                        type="primary"
                        htmlType="submit"
                        className="register-form-button"
                        block
                        style={{ height: 40 }}
                    >
                        注册
                    </Button>
                </Form.Item>

                <div style={{ textAlign: 'center' }}>
                    <Button type="link" onClick={() => navigate('/login')}>
                        已有账号？去登录
                    </Button>
                </div>
            </Form>
        </div>
    );
};

export default Register;
